package com.trek2000.android.enterprise;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.decode.ImageDecoder;

import adapter.group_management.AddMemberToGroupAdapter;
import controller.user_management.GetUserInfoFromContactAsync;
import define.Constants;
import singleton.Item;
import singleton.company.Company;
import singleton.group_management.GroupManagement;
import singleton.setting.Setting;
import ui.activity.custom.gallery.CustomGallery;
import ui.activity.group_management.CreateGroup;
import ui.activity.login.Login;
import ui.activity.user_managament.InviteUserToCompany;
import ui.fragment.company.AllCompanyFeedFragment;
import ui.fragment.company.SelectCompanyFragment;
import ui.fragment.drawer.NavigationDrawerFragment;
import ui.fragment.drawer.NavigationDrawerInNotificationsFragment;
import utils.SmartUriDecoder;


public class Enterprise extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, View.OnClickListener {

    //String seeion
//    public Boolean HAS_ALREADY_GET_DATA_FROM_CONTACT = false;
    /**
     * Image loader to load image flexible, avoid OutOfMemory exception
     */
    public static ImageLoader imageLoader = ImageLoader.getInstance();
    public static ImageLoaderConfiguration imageLoaderConfiguration;

    /**
     * Single ton way
     */
    public static Item item = Item.getInstance();
    public static Company company = Company.getInstance();
    public static Setting setting = Setting.getInstance();
    public static GroupManagement groupManagement = GroupManagement.getInstance();
    /**
     * View section
     */
    public static ImageButton mIbtnInviteUserToCompany;
    public static ImageButton mIbtnCreateGroup;
    private ImageButton mIbtnDrawer;
    public static ImageButton mIbtnUpload;
    public static ImageView mIvArrowInActionBar;
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private NavigationDrawerInNotificationsFragment mNavigationDrawerInNotificationsFragment;
    public static TextView mTvTitle;
    //the others session
    public  static Context mContext;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_invite_user_to_company_in_action_bar:
                /**
                 * Cases
                 * - User management page
                 * - Group name page
                 */
                startActivity(new Intent(this,InviteUserToCompany.class));
                break;
//            case R.id.ibtn_back_in_action_bar:
//                /**
//                 * Cases
//                 * - Add To Group page
//                 * - Country page
//                 * - Company Logo page
//                 * - Group Name page
//                 */
//                break;
            case R.id.ibtn_create_group_in_action_bar:
                /**
                 * - Group Management page
                 */
                startActivity(new Intent(this, CreateGroup.class));
                //reset single ton group manager
                if (Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager() != null &&
                        !Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().isEmpty()) {
                    Enterprise.groupManagement.setmAlPosOfItemCheckedInAddGroupManager(null);
                }
                if (AddMemberToGroupAdapter.mAlPosOfItemCheckedInAddGroupManager != null &&
                        !AddMemberToGroupAdapter.mAlPosOfItemCheckedInAddGroupManager.isEmpty()) {
                    AddMemberToGroupAdapter.mAlPosOfItemCheckedInAddGroupManager.clear();
                }
                //reset single ton member
                if (Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup()!= null &&
                        !Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().isEmpty()) {
                    Enterprise.groupManagement.setmAlPosOfItemCheckedInAddMemberToGroup(null);
                }
                if (AddMemberToGroupAdapter.mAlPosOfItemCheckedInAddMemberToGroup != null &&
                        !AddMemberToGroupAdapter.mAlPosOfItemCheckedInAddMemberToGroup.isEmpty()) {
                    AddMemberToGroupAdapter.mAlPosOfItemCheckedInAddMemberToGroup.clear();
                }
                break;
            case R.id.ibtn_drawer_in_action_bar:
                //check if is in all company feed or select company show NavigationDrawerInNotificationsFragment
                // else if is in company feed show NavigationDrawerFragment
//                Log.i("" ,"AllCompanyFeedFragment.IS_IN_ALL_COMPANY_FEED_FRAGMENT " + AllCompanyFeedFragment.IS_IN_ALL_COMPANY_FEED_FRAGMENT);
//                Log.i("" ,"SelectCompanyFragment.IS_IN_SELECT_COMPANY_FRAGMENT " + SelectCompanyFragment.IS_IN_SELECT_COMPANY_FRAGMENT);
//            if (AllCompanyFeedFragment.IS_IN_ALL_COMPANY_FEED_FRAGMENT ||
//                    SelectCompanyFragment.IS_IN_SELECT_COMPANY_FRAGMENT) {
//                /**
//                 * Check the navigation bar was showing or not
//                 */
//                if (!NavigationDrawerInNotificationsFragment.mViewContainer.isShown()) {
//                    NavigationDrawerInNotificationsFragment.mDrawerLayout
//                            .openDrawer(NavigationDrawerInNotificationsFragment.mViewContainer);
//                } else {
//                    NavigationDrawerInNotificationsFragment.mDrawerLayout
//                            .closeDrawer(NavigationDrawerInNotificationsFragment.mViewContainer);
//                }
//
//            } else {
                //check view for drawer, if is all company or select company, show notification else show company feed drawer
                if (AllCompanyFeedFragment.IS_IN_ALL_COMPANY_FEED_FRAGMENT ||
                        SelectCompanyFragment.IS_IN_SELECT_COMPANY_FRAGMENT){
//                    NavigationDrawerFragment.mLlNavigationDrawerGeneralNotifications.setVisibility(View.VISIBLE);
//                    NavigationDrawerFragment.mLlNavigationDrawerInAllCompanyFeed.setVisibility(View.GONE);
                    NavigationDrawerFragment.mLlCompanyNameInNavigationDrawerInCompanyFeed.setVisibility(View.INVISIBLE);
                    NavigationDrawerFragment.mLvInAllCompanyFeed.setVisibility(View.INVISIBLE);
                } else {
//                    NavigationDrawerFragment.mLlNavigationDrawerInAllCompanyFeed.setVisibility(View.VISIBLE);
//                    NavigationDrawerFragment.mLlNavigationDrawerGeneralNotifications.setVisibility(View.GONE);
                    NavigationDrawerFragment.mLlCompanyNameInNavigationDrawerInCompanyFeed.setVisibility(View.VISIBLE);
                    NavigationDrawerFragment.mLvInAllCompanyFeed.setVisibility(View.VISIBLE);
                }
                /**
                 * Check the navigation bar was showing or not
                 */
                if (!NavigationDrawerFragment.mViewContainer.isShown()) {
                    NavigationDrawerFragment.mDrawerLayout
                            .openDrawer(NavigationDrawerFragment.mViewContainer);
                } else {
                    NavigationDrawerFragment.mDrawerLayout
                            .closeDrawer(NavigationDrawerFragment.mViewContainer);
                }
//            }
                break;
            case R.id.ibtn_upload_in_action_bar:
                /**
                 * Cases
                 * - Group Name page
                 */
                // todo Go to Custom Gallery to upload
                startActivityForResult(new Intent(Enterprise.this, CustomGallery.class), 1000);
                break;
//            case R.id.tv_add_to_group_in_action_bar:
//                /**
//                 * Cases
//                 * - Add To Group page
//                 */
//                break;
//            case R.id.tv_done_in_action_bar:
//                /**
//                 * Cases
//                 * - Create Group page
//                 * - Group Name page
//                 */
//                break;
//            case R.id.tv_download_in_action_bar:
//                /**
//                 * Cases
//                 * - Group Name page
//                 */
//                break;
            case R.id.tv_title_in_action_bar:
                //TODO go to all company fragment
                getSupportFragmentManager().beginTransaction().replace(
                        R.id.fl_in_activity_enterprise, SelectCompanyFragment.newInstance()
                ).commitAllowingStateLoss();
                mTvTitle.setText(getString(R.string.all_company));
                mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_up);
                mIvArrowInActionBar.setVisibility(View.VISIBLE);
                break;

        }
    }
    /**
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enterprise);
        mContext = this;
        Log.i("","Login.user.getDeviceToken() " + Login.user.getDeviceToken());
        /**
         * Action Bar
         */
        Constants.mAb = getSupportActionBar();
        Constants.mAb.setDisplayShowHomeEnabled(false);
        Constants.mAb.setDisplayShowTitleEnabled(false);

        Constants.mAb.setDisplayHomeAsUpEnabled(false);

        Constants.mAb.setDisplayShowCustomEnabled(true);


        // Set Custom Action Bar (Should locate after initialized)
        Constants.mAb.setCustomView(R.layout.action_bar);

//        View v = getSupportActionBar().getCustomView();
//        ViewGroup.LayoutParams lp = v.getLayoutParams();
//        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
//        v.setLayoutParams(lp);

        // Show action bar
        Constants.mAb.show();

        // Set title is null
        setTitle("");

        ImageDecoder smartUriDecoder = new SmartUriDecoder(
                getContentResolver(), new BaseImageDecoder(false));

        // This configuration tuning is custom.
        // You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method
        imageLoaderConfiguration =
                new ImageLoaderConfiguration.Builder(this)
                        .threadPriority(Thread.NORM_PRIORITY - 2)
                        .denyCacheImageMultipleSizesInMemory()
                        .diskCacheFileNameGenerator(new Md5FileNameGenerator())
                        .diskCacheSize(50 * 1024 * 1024) // 50 Mb.
//                        .imageDecoder(smartUriDecoder)
                        .tasksProcessingOrder(QueueProcessingType.LIFO)
                        .writeDebugLogs() // Remove for release app
                        .build();
        // Initialize ImageLoader with configuration.
        imageLoader.init(imageLoaderConfiguration);

        /**
         * If the user has not signed in yet,
         * should directly to sign in page
         */
//        mSp = getSharedPreferences(PREFS, 1);
//        mSpEditor = mSp.edit();

        initialVariables();
        initialData();
        //only get data from contact one time, not reset HAS_ALREADY_GET_DATA_FROM_CONTACT
//        if (!HAS_ALREADY_GET_DATA_FROM_CONTACT) {
//            getDataFromContact();
//            HAS_ALREADY_GET_DATA_FROM_CONTACT = true;
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Login.IS_LOGIN_BY_FACEBOOK = false;
        Login.IS_LOGIN_BY_GOOGLE_PLUS = false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        Login.IS_LOGIN_BY_FACEBOOK = false;
        Login.IS_LOGIN_BY_GOOGLE_PLUS = false;
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
    }

    /**
     * Initialize variables
     */

    private void initialData() {
        // Set listener
        mIbtnInviteUserToCompany.setOnClickListener(this);
        mIbtnCreateGroup.setOnClickListener(this);
        mIbtnDrawer.setOnClickListener(this);
        mIbtnUpload.setOnClickListener(this);
        mTvTitle.setOnClickListener(this);

        // Set up the Drawer Layout.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

//        // Set up the Drawer Layout.
//        mNavigationDrawerInNotificationsFragment.setUp(
//                R.id.navigation_drawer_in_notifications,
//                (DrawerLayout) findViewById(R.id.drawer_layout_in_notifications));

        //load all company feed
        loadAllCompanyFeed();

//        loadSelectCompany();
    }
    private void initialVariables() {
        mIbtnInviteUserToCompany = (ImageButton) findViewById(R.id.ibtn_invite_user_to_company_in_action_bar);
        mIbtnCreateGroup = (ImageButton) findViewById(R.id.ibtn_create_group_in_action_bar);
        mIbtnDrawer = (ImageButton) findViewById(R.id.ibtn_drawer_in_action_bar);
        mIbtnUpload = (ImageButton) findViewById(R.id.ibtn_upload_in_action_bar);
        mIvArrowInActionBar = (ImageView) findViewById(R.id.iv_arrow_in_action_bar);
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

//        mNavigationDrawerInNotificationsFragment = (NavigationDrawerInNotificationsFragment)
//                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_in_notifications);

        mTvTitle = (TextView) findViewById(R.id.tv_title_in_action_bar);
    }

    /**
     * Basic methods
     */
    private void loadAllCompanyFeed() {
        getSupportFragmentManager().beginTransaction().replace(
                R.id.fl_in_activity_enterprise, AllCompanyFeedFragment.newInstance()
        ).commitAllowingStateLoss();
        mIvArrowInActionBar.setImageResource(R.drawable.iv_arrow_down);
        mIvArrowInActionBar.setVisibility(View.VISIBLE);
    }
    //TODO load background select company to get data, because not yet drawer notification (drawer company just open in company feed)
//    private void loadSelectCompany() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
//            new SelectCompanyAsync(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
//                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
//                    Login.user.getUserInfo().getAccessToken());
//        else
//            new SelectCompanyAsync(this).execute(
//                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
//                    Login.user.getUserInfo().getAccessToken());
//    }
    //get contact when login succes, because it take long time
//    private void getDataFromContact () {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
//            new GetUserInfoFromContactAsync(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//        else
//            new GetUserInfoFromContactAsync(this).execute();
//    }
}
